//
// Created by 孟令涛 on 24-7-15.
//
#include "UltrasonicTask.h"
#include "GlobalVars.h"
#include <string.h>
#include <stdio.h>
#include "utils.h"
#include "cmsis_os.h"
#include "usart.h"
#include "tim.h"
#include "stm32f1xx_hal.h"


#define TIMEOUT_MS 100  // 设置超时时间为100毫秒


void HC_SR04_Init(void) {
    // GPIO已经在CubeMX中配置，这里不需要重复配置

    // 配置TIM2
    HAL_TIM_Base_Start_IT(&htim2);
}

//void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
//    if (htim->Instance == TIM2) {
//        Y_Out_Counter++;
//    }
//}

static void Timer_On(void) {
    __HAL_TIM_SET_COUNTER(&htim2, 0);
    Y_Out_Counter = 0;
    HAL_TIM_Base_Start(&htim2);
}

static void Timer_Off(void) {
    HAL_TIM_Base_Stop(&htim2);
}

static uint32_t Timer_Get_Counter(void) {
    uint32_t T;
    T = Y_Out_Counter * 100;
    T += __HAL_TIM_GET_COUNTER(&htim2);
    __HAL_TIM_SET_COUNTER(&htim2, 0);
    osDelay(50);
    return T;
}

float HC_SR04_GetLength(void) {
    int i;
    uint32_t t = 0;
    float Length = 0;
    float Sum = 0;

    for (i = 0; i < 3; i++) {
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, GPIO_PIN_SET);
        osDelay(1);
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, GPIO_PIN_RESET);

        // 添加超时保护
        uint32_t start_time = HAL_GetTick();
        while (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_12) == GPIO_PIN_RESET) {
            if (HAL_GetTick() - start_time > TIMEOUT_MS) {
                // 超时，返回一个错误值
                return -1.0f;
            }
        }

        Timer_On();

        // 再次添加超时保护
        start_time = HAL_GetTick();
        while (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_12) == GPIO_PIN_SET) {
            if (HAL_GetTick() - start_time > TIMEOUT_MS) {
                // 超时，返回一个错误值
                return -1.0f;
            }
        }

        Timer_Off();

        t = Timer_Get_Counter();

        Length = ((float) t / 58.0);

        Sum += Length;
    }

    Length = Sum / 3.0;
    return Length;
}


void UltrasonicTask(void const *argument) {
    for (;;) {
        distance = HC_SR04_GetLength();
        if (distance < JinJuLi) {
            beepState = 0;
        } else if (distance >= JinJuLi && distance < ZhongJuLi) {
            beepState = 1;
        } else if (distance >= ZhongJuLi && distance < YuanJuLi) {
            beepState = 2;
        } else {
            beepState = 3;
        }
        // ʹ��distance���к�������
        osDelay(1000);  // ÿ�����һ��
    }
}
